package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.dialog.PopupDropDownBoxWindow;
import com.cj.mobile.iabp.app.global.Constant;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.DecimalInputUtils;
import com.cj.mobile.iabp.app.utils.EventBusTags;
import com.cj.mobile.iabp.app.utils.GlideLoader;
import com.cj.mobile.iabp.di.component.DaggerAddRoundsInfoComponent;
import com.cj.mobile.iabp.mvp.contract.AddRoundsInfoContract;
import com.cj.mobile.iabp.mvp.model.entity.DictInfo;
import com.cj.mobile.iabp.mvp.model.entity.MainEvent;
import com.cj.mobile.iabp.mvp.model.entity.RoundsInfo;
import com.cj.mobile.iabp.mvp.presenter.AddRoundsInfoPresenter;
import com.cj.mobile.iabp.mvp.ui.adapter.UploadCertificateAdapter;
import com.cj.mobile.iabp.mvp.ui.widget.FlexboxRadioGroup;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.lcw.library.imagepicker.ImagePicker;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created on 2025/09/28 15:20
 * 添加查房信息
 *
 * @author Love_xie
 * module name is AddRoundsInfoActivity
 */
@RuntimePermissions
public class AddRoundsInfoActivity extends BaseActivity<AddRoundsInfoPresenter> implements AddRoundsInfoContract.View {
    /*----------------------------------------------------------------控件信息----------------------------------------------------------------*/
    @BindView(R.id.txvi_addroundsinfo_code)
    TextView txviCode;                                                                              // 登记号
    @BindView(R.id.txvi_addroundsinfo_name)
    TextView txviName;                                                                              // 患者姓名
    @BindView(R.id.edit_addroundsinfo_ward)
    EditText editWard;                                                                              // 查房时所在病房
    @BindView(R.id.edit_addroundsinfo_bunk)
    EditText editBunk;                                                                              // 查房时所在床位
    @BindView(R.id.lila_addroundsinfo_input_wardrounds)
    LinearLayout lilaWardRounds;
    @BindView(R.id.edit_addroundsinfo_input_wardrounds)
    EditText editWardRounds;                                                                        // 查房人员

    @BindView(R.id.group_addroundsinfo_xpwz)
    FlexboxRadioGroup rgXpwz;                                                                       // 胸片位置
    @BindView(R.id.edit_addsurgeryinfo_xpzdlj)
    EditText editXpzdlj;                                                                            // 胸片位置调整
    @BindView(R.id.txvi_addroundsinfo_roundtime)
    TextView txviRoundTime;                                                                         // 查房时间
    @BindView(R.id.imvi_addroundsinfo_roundtime)
    ImageView imviRoundTime;
    @BindView(R.id.group_addroundsinfo_fbxg)
    RadioGroup rgFbxg;                                                                              // 反搏效果
    @BindView(R.id.group_addroundsinfo_gssl)
    RadioGroup rgGssl;                                                                              // 肝素水量
    @BindView(R.id.group_addroundsinfo_yldyl)
    RadioGroup rgYldyl;                                                                             // 压力带压力
    @BindView(R.id.group_addroundsinfo_hql)
    RadioGroup rgHql;                                                                               // 氦气量

    @BindView(R.id.cb_addsurgeryinfo_azc_pwl)
    CheckBox cbAzcPwl;                                                                              // 安装侧
    @BindView(R.id.cb_addsurgeryinfo_azc_pwn)
    CheckBox cbAzcPwn;
    @BindView(R.id.cb_addsurgeryinfo_azc_zbkcj)
    CheckBox cbAzcZbkcj;
    @BindView(R.id.cb_addsurgeryinfo_azc_zbbkcj)
    CheckBox cbAzcZbbkcj;
    @BindView(R.id.cb_addsurgeryinfo_azc_xzfh)
    CheckBox cbAzcXzfh;
    @BindView(R.id.cb_addsurgeryinfo_azc_wjfh)
    CheckBox cbAzcWjfh;
    @BindView(R.id.cb_addsurgeryinfo_azc_crtdy)
    CheckBox cbAzcCrtdy;
    @BindView(R.id.cb_addsurgeryinfo_azc_crtxy)
    CheckBox cbAzcCrtxy;


    @BindView(R.id.cb_addsurgeryinfo_dc_pwl)
    CheckBox cbDcPwl;                                                                               // 对侧
    @BindView(R.id.cb_addsurgeryinfo_dc_pwn)
    CheckBox cbDcPwn;
    @BindView(R.id.cb_addsurgeryinfo_dc_zbkcj)
    CheckBox cbDcZbkcj;
    @BindView(R.id.cb_addsurgeryinfo_dc_zbbkcj)
    CheckBox cbDcZbbkcj;
    @BindView(R.id.cb_addsurgeryinfo_dc_xzfh)
    CheckBox cbDcXzfh;
    @BindView(R.id.cb_addsurgeryinfo_dc_wjfh)
    CheckBox cbDcWjfh;
    @BindView(R.id.cb_addsurgeryinfo_dc_crtdy)
    CheckBox cbDcCrtdy;
    @BindView(R.id.cb_addsurgeryinfo_dc_crtxy)
    CheckBox cbDcCrtxy;


    @BindView(R.id.group_addroundsinfo_ecmo)
    RadioGroup rgEcmo;                                                                              // ECMO时机
    @BindView(R.id.edit_addsurgeryinfo_machinecode)
    EditText editMachineCode;                                                                       // 机器代码
    @BindView(R.id.edit_addroundsinfo_special)
    EditText editSpecial;                                                                           // 特殊情况需详述
    @BindView(R.id.revi_addroundsinfo_img)
    RecyclerView reviImgList;                                                                       // 特殊或异常情况拍照
    @BindView(R.id.txvi_addroundsinfo_inspection)
    TextView txviInspection;                                                                        // 检验日期
    @BindView(R.id.imvi_addroundsinfo_inspection)
    ImageView imviInspection;

    @BindView(R.id.edit_addroundsinfo_ast)
    EditText editAst;                                                                               // AST
    @BindView(R.id.edit_addroundsinfo_alt)
    EditText editAlt;                                                                               // ALT
    @BindView(R.id.edit_addroundsinfo_cr)
    EditText editCr;                                                                                // 肌酐
    @BindView(R.id.edit_addroundsinfo_egfr)
    EditText editEgfr;                                                                              // eGFR
    @BindView(R.id.edit_addroundsinfo_myo)
    EditText editMyo;                                                                               // 肌红蛋白
    @BindView(R.id.edit_addroundsinfo_clac)
    EditText editClac;                                                                              // 乳酸cLac
    @BindView(R.id.edit_addroundsinfo_myog)
    EditText editMyog;                                                                              // 肌钙蛋白
    @BindView(R.id.edit_addroundsinfo_zsszmqnj)
    EditText editZsszmqnj;                                                                          // 左室舒张末期内径
    @BindView(R.id.edit_addroundsinfo_zssxfs)
    EditText editZssxfs;                                                                            // 左室射血分数

    /*----------------------------------------------------------------业务信息----------------------------------------------------------------*/
    // 对话框
    private MaterialDialog mDialog;
    // 查房时间，检验日期
    private Date roundsData, inspectionData;

    // 选择查房人员
    private PopupDropDownBoxWindow mPopupRoundsPersonnel;
    @Inject
    UploadCertificateAdapter mImgAdapter;
    @Inject
    GridLayoutManager mGridLayoutManager;

    @Override
    protected void onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        DefaultAdapter.releaseAllHolder(reviImgList);
        if (mDialog != null) {
            this.mDialog.dismiss();
        }
        super.onDestroy();

        this.mDialog = null;
        this.mImgAdapter = null;
        this.mGridLayoutManager = null;
        this.roundsData = null;
        this.inspectionData = null;
        if (this.mPopupRoundsPersonnel != null) {
            this.mPopupRoundsPersonnel.dismiss();
            this.mPopupRoundsPersonnel = null;
        }
    }

    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerAddRoundsInfoComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_add_rounds_info;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        setTitle("查房信息");

        roundsData = new Date();
        inspectionData = new Date();

        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.common_execute).progress(true, 0).build();

        initRecyclerView();
        setupListeners();

        // 创建输入框数组
        EditText[] decimalInputs = {editAst, editAlt, editCr, editEgfr, editMyo, editClac, editMyog, editZsszmqnj, editZssxfs};
        // 批量设置，限制小数点后2位
        DecimalInputUtils.setupDecimalInputs(decimalInputs, 2);

        if (mPresenter != null) {
            mPresenter.initData(getIntent().getExtras());
        }
    }

    private void initRecyclerView() {
        ArmsUtils.configRecyclerView(reviImgList, mGridLayoutManager);
        reviImgList.setAdapter(mImgAdapter);
        mImgAdapter.setDefaultBg(false);
    }

    private void setupListeners() {
        // EditText 点击监听 - 显示PopupWindow和所有数据
        editWardRounds.setOnClickListener(v -> {
            mPopupRoundsPersonnel.showAllData();
            mPopupRoundsPersonnel.show();
        });

        // EditText 文本变化监听 - 实时筛选
        editWardRounds.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 实时筛选数据
                if (mPopupRoundsPersonnel != null) {
                    mPopupRoundsPersonnel.filterData(s.toString());

                    // 如果PopupWindow没有显示，则显示它
                    if (!mPopupRoundsPersonnel.isShowing()) {
                        mPopupRoundsPersonnel.show();
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        // EditText 焦点变化监听
        editWardRounds.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                // 获取焦点时，如果文本为空，显示所有数据
                if (TextUtils.isEmpty(editWardRounds.getText())) {
                    mPopupRoundsPersonnel.showAllData();
                    mPopupRoundsPersonnel.show();
                }
            } else {
                // 失去焦点时，延迟隐藏PopupWindow，避免与item点击冲突
                editWardRounds.postDelayed(() -> {
                    if (!editWardRounds.hasFocus()) {
                        mPopupRoundsPersonnel.dismiss();
                    }
                }, 200);
            }
        });

        // 处理键盘完成按钮
//        editWardRounds.setOnEditorActionListener((v, actionId, event) -> {
//            if (actionId == EditorInfo.IME_ACTION_DONE) {
//                mPopupRoundsPersonnel.dismiss();
//                hideInput();
//                return true;
//            }
//            return false;
//        });
    }

    @OnClick({
            R.id.lila_addroundsinfo_roundtime,                                                      // 查房时间
            R.id.imvi_addroundsinfo_roundtime,
            R.id.lila_addroundsinfo_inspection,                                                     // 检验日期
            R.id.imvi_addroundsinfo_inspection,
            R.id.btn_addroundsinfo_save,                                                            // 保存
            R.id.btn_addroundsinfo_submit,                                                          // 提交
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lila_addroundsinfo_roundtime:                                                 // 查房时间
                onSoundsDate();
                break;
            case R.id.imvi_addroundsinfo_roundtime:
                txviRoundTime.setText("");
                imviRoundTime.setVisibility(View.GONE);
                break;
            case R.id.lila_addroundsinfo_inspection:                                                // 检验日期
                onInspectionDate();
                break;
            case R.id.imvi_addroundsinfo_inspection:
                txviInspection.setText("");
                imviInspection.setVisibility(View.GONE);
                break;
            case R.id.btn_addroundsinfo_save:                                                       // 保存
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("0");
                }
                break;
            case R.id.btn_addroundsinfo_submit:                                                     // 提交
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("1");
                }
                break;
        }
    }

    /**
     * 暂存和提交事件
     *
     * @param pre
     */
    private void onSubmit(String pre) {
        if (mPresenter != null) {
            mPresenter.btnSubmit(pre,
                    editWardRounds.getText().toString(),
                    editWardRounds.getText().toString(),
                    getXpwzChecked(),
                    editXpzdlj.getText().toString(),
                    txviRoundTime.getText().toString(),
                    getFb(),
                    getGss(),
                    getYldyl(),
                    getHql(),
                    getLessL(), getLessR(),
                    getEcmo(),
                    editMachineCode.getText().toString(),
                    editSpecial.getText().toString(),
                    txviInspection.getText().toString(),
                    editAst.getText().toString(),
                    editAlt.getText().toString(),
                    editCr.getText().toString(),
                    editEgfr.getText().toString(),
                    editMyo.getText().toString(),
                    editClac.getText().toString(),
                    editMyog.getText().toString(),
                    editZsszmqnj.getText().toString(),
                    editZssxfs.getText().toString(),
                    mImgAdapter.getInfos()
            );
        }
    }

    private List<String> getLessL() {
        List<String> lessL = new ArrayList<>();
        if (cbAzcPwl.isChecked()) {
            lessL.add("皮温凉");
        }
        if (cbAzcPwn.isChecked()) {
            lessL.add("皮温暖");
        }
        if (cbAzcZbkcj.isChecked()) {
            lessL.add("足背可触及");
        }
        if (cbAzcZbbkcj.isChecked()) {
            lessL.add("足背不可触及");
        }
        if (cbAzcXzfh.isChecked()) {
            lessL.add("下肢发花");
        }
        if (cbAzcWjfh.isChecked()) {
            lessL.add("未见发花");
        }
        if (cbAzcCrtdy.isChecked()) {
            lessL.add("CRT>3s");
        }
        if (cbAzcCrtxy.isChecked()) {
            lessL.add("CRT<3s");
        }
        return lessL;
    }

    private List<String> getLessR() {
        List<String> lessR = new ArrayList<>();
        if (cbDcPwl.isChecked()) {
            lessR.add("皮温凉");
        }
        if (cbDcPwn.isChecked()) {
            lessR.add("皮温暖");
        }
        if (cbDcZbkcj.isChecked()) {
            lessR.add("足背可触及");
        }
        if (cbDcZbbkcj.isChecked()) {
            lessR.add("足背不可触及");
        }
        if (cbDcXzfh.isChecked()) {
            lessR.add("下肢发花");
        }
        if (cbDcWjfh.isChecked()) {
            lessR.add("未见发花");
        }
        if (cbDcCrtdy.isChecked()) {
            lessR.add("CRT>3s");
        }
        if (cbDcCrtxy.isChecked()) {
            lessR.add("CRT<3s");
        }
        return lessR;
    }

    private String getEcmo() {
        if (rgEcmo.getCheckedRadioButtonId() != -1) {
            if (rgEcmo.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_ecmo_not) {
                // 正常
                return "无";
            } else {
                // 异常
                return "有";
            }
        }
        return "";
    }

    /**
     * 氦气量
     */
    private String getHql() {
        if (rgHql.getCheckedRadioButtonId() != -1) {
            if (rgHql.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_hql_wxgh) {
                // 正常
                return "无需更换";
            } else {
                // 异常
                return "需更换";
            }
        }
        return "";
    }

    /**
     * 压力带压力
     */
    private String getYldyl() {
        if (rgYldyl.getCheckedRadioButtonId() != -1) {
            if (rgYldyl.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_yldyl_normal) {
                // 正常
                return "正常";
            } else {
                // 异常
                return "异常";
            }
        }
        return "";
    }

    /**
     * 肝素水量
     */
    private String getGss() {
        if (rgGssl.getCheckedRadioButtonId() != -1) {
            if (rgGssl.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_gssl_wxgh) {
                // 正常
                return "无需更换";
            } else {
                // 异常
                return "需更换";
            }
        }
        return "";
    }

    /**
     * 获取反搏效果
     */
    private String getFb() {
        if (rgFbxg.getCheckedRadioButtonId() != -1) {
            if (rgFbxg.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_fbxg_normal) {
                // 正常
                return "正常";
            } else {
                // 异常
                return "异常";
            }
        }

        return "";
    }

    /**
     * 获取胸片位置
     */
    private String getXpwzChecked() {
        if (rgXpwz.getCheckedRadioButtonId() != -1) {
            if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_1) {
                return "1";
            } else if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_2) {
                return "2";
            } else if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_3) {
                return "3";
            } else if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_4) {
                return "4";
            } else if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_5) {
                return "5";
            } else if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_6) {
                return "6";
            } else if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_7) {
                return "7";
            } else if (rgXpwz.getCheckedRadioButtonId() == R.id.radio_addsurgeryinfo_xpwz_8) {
                return "8";
            }
        }

        return "";
    }

    /**
     * 检验日期
     */
    private void onInspectionDate() {
        // 起始日期
        Calendar startDate = Calendar.getInstance();
        // 设置年份
        startDate.set(Calendar.YEAR, 1900);

        // 终止日期(今天+100年)
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.YEAR, 100);

        TimePickerView pvOptions = new TimePickerView.Builder(this, (date, v) -> {
            this.inspectionData = date;
            // yyyy-MM-dd HH:mm:ss
            txviInspection.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd")));
            imviInspection.setVisibility(View.VISIBLE);
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(20)//确定和取消文字大小
                .setSubmitColor(ContextCompat.getColor(this, R.color.colorPrimary))//确定按钮文字颜色
                .setCancelColor(ContextCompat.getColor(this, R.color.colorPrimary))//取消按钮文字颜色
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
//                .setCyclic(true, true, true)//循环与否
                .setType(new boolean[]{true, true, true, false, false, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
                .setRangDate(startDate, endDate)
                .build();

        // 设置数据
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inspectionData);
        pvOptions.setDate(calendar);
        pvOptions.show();
    }

    /**
     * 查房时间
     */
    private void onSoundsDate() {
        // 起始日期
        Calendar startDate = Calendar.getInstance();
        // 设置年份
        startDate.set(Calendar.YEAR, 1900);

        // 终止日期(今天+100年)
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.YEAR, 100);

        TimePickerView pvOptions = new TimePickerView.Builder(this, (date, v) -> {
            this.roundsData = date;
            // yyyy-MM-dd HH:mm:ss
            txviRoundTime.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm")));
            imviRoundTime.setVisibility(View.VISIBLE);
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(20)//确定和取消文字大小
                .setSubmitColor(ContextCompat.getColor(this, R.color.colorPrimary))//确定按钮文字颜色
                .setCancelColor(ContextCompat.getColor(this, R.color.colorPrimary))//取消按钮文字颜色
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
//                .setCyclic(true, true, true)//循环与否
                .setType(new boolean[]{true, true, true, true, true, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
                .setRangDate(startDate, endDate)
                .setContentSize(16)
                .build();

        // 设置数据
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(roundsData);
        pvOptions.setDate(calendar);
        pvOptions.show();
    }

    @Subscriber(tag = EventBusTags.HOME_TAG, mode = ThreadMode.POST)
    private void eventBusEvent(MainEvent mainEvent) {
        if (mainEvent.getCode() == EventBusTags.UPLOAD_IMAGE_TAG) {
            // 上传图片
            AddRoundsInfoActivityPermissionsDispatcher.getCameraWithPermissionCheck(this);
        } else if (mainEvent.getCode() == EventBusTags.DELETE_IMAGE_TAG) {
            // 删除照片
            if (mImgAdapter != null) {
                mImgAdapter.getInfos().remove(mainEvent.getPosition());
                mImgAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 选择图片
     */
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void getCamera() {
        FileUtils.createOrExistsDir(Constant.IMAGE_PATH);

        ImagePicker.getInstance()
                .setTitle("图片")//设置标题
                .showCamera(true)//设置是否显示拍照按钮
                .showImage(true)//设置是否展示图片
                .showVideo(false)//设置是否展示视频
                .filterGif(true)//设置是否过滤gif图片
                .setMaxCount(getImageNum())//设置最大选择图片数目(默认为1，单选)
                .setSingleType(true)//设置图片视频不能同时选择
                .setImagePaths(galleryImages)
                .setImageLoader(new GlideLoader(getApplicationContext()))//设置自定义图片加载器
                .start(this, Constant.SELECT_IMG_GSMT_REQUESTCODE);
    }


    // 图库图片
    private ArrayList<String> galleryImages = new ArrayList<>();
    // 网络图片
    private ArrayList<String> networkImages = new ArrayList<>();

    /**
     * 图片可选数量
     * 逻辑：共可以选3张，假设列表中存在网络图片，则需要减去已存在的图片数量
     */
    private int getImageNum() {
        galleryImages.clear();
        networkImages.clear();
        // 一共可选图片数量
        int total = 3;
        // 网络图片数量
        int networkNum = 0;

        for (String str : mImgAdapter.getInfos()) {
            if (str.contains("http")) {
                networkNum++;
                networkImages.add(str);
            } else {
                galleryImages.add(str);
            }
        }

        return total - networkNum;
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCameraDenied() {
        // 用户拒绝权限时的处理
        showMessage("需要相机和存储权限才能选择图片");
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCameraNeverAskAgain() {
        // 用户选择"不再询问"时的处理
        new MaterialDialog.Builder(this)
                .content("需要相机和存储权限才能选择图片，请在设置中手动开启权限")
                .positiveText("去设置")
                .negativeText("取消")
                .onPositive((dialog, which) -> {
                    // 引导用户到应用设置页面开启权限
                    CommonUtils.goToAppSettings(this);
                })
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 照片
            if (requestCode == Constant.SELECT_IMG_GSMT_REQUESTCODE) {
                // 清空以前图片
                mImgAdapter.getInfos().clear();
                // 展示图片
                uploadData(data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES), requestCode);
            }
        }
    }

    /**
     * 压缩失败 》 加载图片 》 添加默认选择的图片
     */
    private void uploadData(ArrayList<String> path, int requestCode) {
        // 照片
        if (requestCode == Constant.SELECT_IMG_GSMT_REQUESTCODE) {
            // 接收当前选中的图
            mImgAdapter.setData(networkImages);
            mImgAdapter.setData(path);
            // 接下来展示图片
            mImgAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddRoundsInfoActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void hideLoadingSubmit() {
        if (mDialog != null)
            mDialog.cancel();
    }

    @Override
    public void showLoadingSubmit() {
        if (mDialog != null)
            mDialog.show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void showSurgeryInfo(String code, String name, String area, String bedNo, String machineCode, RoundsInfo info) {
        txviCode.setText(CommonUtils.isEmptyReturnStr(code, "暂无"));
        txviName.setText(CommonUtils.isEmptyReturnStr(name));
        editWard.setText(CommonUtils.isEmptyReturnStr(area));
        editBunk.setText(CommonUtils.isEmptyReturnStr(bedNo));

        // 机器代码
        editMachineCode.setText(CommonUtils.isEmptyReturnStr(machineCode));

        if (info != null) {
            // 当前为编辑状态
            editWardRounds.setText(CommonUtils.isEmptyReturnStr(info.getDoctorName()));

            // 胸片
            if (!TextUtils.isEmpty(info.getPlace1())) {
                switch (info.getPlace1()) {
                    case "1":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_1)).setChecked(true);
                        break;
                    case "2":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_2)).setChecked(true);
                        break;
                    case "3":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_3)).setChecked(true);
                        break;
                    case "4":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_4)).setChecked(true);
                        break;
                    case "5":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_5)).setChecked(true);
                        break;
                    case "6":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_6)).setChecked(true);
                        break;
                    case "7":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_7)).setChecked(true);
                        break;
                    case "8":
                        ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_xpwz_8)).setChecked(true);
                        break;
                }
            }

            editXpzdlj.setText(CommonUtils.isEmptyReturnStr(info.getPlace2()));
            txviRoundTime.setText(CommonUtils.isEmptyReturnStr(info.getRoundTime()));
            imviRoundTime.setVisibility(View.VISIBLE);

            // 反搏
            if (!TextUtils.isEmpty(info.getFbType())) {
                if (info.getFbType().equals("正常")) {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_fbxg_normal)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_fbxg_abnormal)).setChecked(true);
                }
            }

            if (!TextUtils.isEmpty(info.getGssType())) {
                if (info.getGssType().equals("无需更换")) {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_gssl_wxgh)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_gssl_xygh)).setChecked(true);
                }
            }

            if (!TextUtils.isEmpty(info.getYali())) {
                if (info.getYali().equals("正常")) {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_yldyl_normal)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_yldyl_abnormal)).setChecked(true);
                }
            }

            if (!TextUtils.isEmpty(info.getHaiqi())) {
                if (info.getHaiqi().equals("无需更换")) {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_hql_wxgh)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_hql_xygh)).setChecked(true);
                }
            }

            if (!TextUtils.isEmpty(info.getLessL())) {
                String[] lessL = info.getLessL().split(",");
                for (int i = 0; i < lessL.length; i++) {
                    switch (lessL[i]) {
                        case "皮温凉":
                            cbAzcPwl.setChecked(true);
                            break;
                        case "皮温暖":
                            cbAzcPwn.setChecked(true);
                            break;
                        case "足背可触及":
                            cbAzcZbkcj.setChecked(true);
                            break;
                        case "足背不可触及":
                            cbAzcZbbkcj.setChecked(true);
                            break;
                        case "下肢发花":
                            cbAzcXzfh.setChecked(true);
                            break;
                        case "未见发花":
                            cbAzcWjfh.setChecked(true);
                            break;
                        case "CRT>3s":
                            cbAzcCrtdy.setChecked(true);
                            break;
                        case "CRT<3s":
                            cbAzcCrtxy.setChecked(true);
                            break;
                    }
                }
            }


            if (!TextUtils.isEmpty(info.getLessR())) {
                String[] lessR = info.getLessR().split(",");
                for (int i = 0; i < lessR.length; i++) {
                    switch (lessR[i]) {
                        case "皮温凉":
                            cbDcPwl.setChecked(true);
                            break;
                        case "皮温暖":
                            cbDcPwn.setChecked(true);
                            break;
                        case "足背可触及":
                            cbDcZbkcj.setChecked(true);
                            break;
                        case "足背不可触及":
                            cbDcZbbkcj.setChecked(true);
                            break;
                        case "下肢发花":
                            cbDcXzfh.setChecked(true);
                            break;
                        case "未见发花":
                            cbDcWjfh.setChecked(true);
                            break;
                        case "CRT>3s":
                            cbDcCrtdy.setChecked(true);
                            break;
                        case "CRT<3s":
                            cbDcCrtxy.setChecked(true);
                            break;
                    }
                }
            }

            if (!TextUtils.isEmpty(info.getEcmo())) {
                if (info.getEcmo().equals("无")) {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_ecmo_not)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addsurgeryinfo_ecmo_yes)).setChecked(true);
                }
            }

            // 如果查房信息中没有机器代码，则显示手术中的机器代码
            if (!TextUtils.isEmpty(info.getMashine())) {
                // 查房中机器代码
                editMachineCode.setText(info.getMashine());
            }

            editSpecial.setText(CommonUtils.isEmptyReturnStr(info.getSpecial()));
            if (!TextUtils.isEmpty(info.getCheckTime())) {
                txviInspection.setText(info.getCheckTime());
                imviInspection.setVisibility(View.VISIBLE);
            }

            editAst.setText(CommonUtils.isEmptyReturnStr(info.getAst()));
            editAlt.setText(CommonUtils.isEmptyReturnStr(info.getAlt()));
            editCr.setText(CommonUtils.isEmptyReturnStr(info.getCr()));
            editEgfr.setText(CommonUtils.isEmptyReturnStr(info.getEgfr()));
            editMyo.setText(CommonUtils.isEmptyReturnStr(info.getMyo()));
            editClac.setText(CommonUtils.isEmptyReturnStr(info.getClac()));
            editMyog.setText(CommonUtils.isEmptyReturnStr(info.getGa()));
            editZsszmqnj.setText(CommonUtils.isEmptyReturnStr(info.getLeftSize()));
            editZssxfs.setText(CommonUtils.isEmptyReturnStr(info.getLeftScore()));

            if (!TextUtils.isEmpty(info.getImages())) {
                String[] path = info.getImages().split(",");

                // 接收当前选中的图
                mImgAdapter.setData(path);
                // 接下来展示图片
                mImgAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void loadWardRounds(List<DictInfo> list) {
        List<String> listName = new ArrayList<>();

        if (CommonUtils.isNotEmpty(list)) {
            for (DictInfo info : list) {
                listName.add(info.getValue());
            }
        }
        mPopupRoundsPersonnel = new PopupDropDownBoxWindow(this, lilaWardRounds, editWardRounds, listName);
    }
}